package cc.rengu.redp.system.service.impl;

import cc.rengu.redp.system.dao.RoleMenuMapper;
import cc.rengu.redp.system.domain.Menu;
import cc.rengu.redp.system.domain.RoleMenu;
import cc.rengu.redp.system.service.MenuService;
import cc.rengu.redp.system.service.RoleMenuServie;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service("roleMenuService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuServie {

    @Autowired
    MenuService menuService;

    @Override
    @Transactional
    public void deleteRoleMenusByRoleId(String[] roleIds) {
        List<Long> list = Arrays.stream(roleIds).map(i -> Long.valueOf(i)).collect(Collectors.toList());
        baseMapper.delete(new LambdaQueryWrapper<RoleMenu>().in(RoleMenu::getRoleId, list));
    }

    @Override
    @Transactional
    public void deleteRoleMenusByMenuId(String[] menuIds) {
        List<Long> list = Arrays.stream(menuIds).map(i -> Long.valueOf(i)).collect(Collectors.toList());
        baseMapper.delete(new LambdaQueryWrapper<RoleMenu>().in(RoleMenu::getMenuId, list));
    }

    @Override
    public List<RoleMenu> getRoleMenusByRoleId(String roleId) {
        //加载角色菜单时过滤掉所有父节点
        QueryWrapper<Menu> lqw = new QueryWrapper<>();
        lqw.select("DISTINCT parent_id");
        List<Menu> parentMenus = menuService.list(lqw);
        List<Long> parentMenuIds = new ArrayList<>();
        parentMenus.forEach(menu -> parentMenuIds.add(menu.getParentId()));
        return baseMapper.selectList(new LambdaQueryWrapper<RoleMenu>()
                .eq(RoleMenu::getRoleId, Long.valueOf(roleId))
                .notIn(RoleMenu::getMenuId, parentMenuIds));
    }
}
